package org.jeecg.modules.login.handler.wechat;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;

/**
 * 微信小程序执行器
 *
 * @author tianyi.jiang
 * @since 1.0.0
 */
@Slf4j
@Component
@ConditionalOnExpression("'${basicplatform.wechat.mini-program.enable:false}'.equals('true')")
public class WechatMiniProgramHandler {

    private final WechatMiniProgramProperty wechatMiniProgramProperty;

    /**
     * 基于"js_code"获取"openId"
     *
     * @param jsCode 登录时获取的"code"(通过wx.login获取)
     * @return Open Id
     */
    public String getOpenId(@Nonnull String jsCode) throws WxErrorException {
        WxMaJscode2SessionResult wxMaJscode2SessionResult = wechatMiniProgramProperty.getWxMaService().jsCode2SessionInfo(jsCode);
        return wxMaJscode2SessionResult.getOpenid();
    }

    /**
     * 获取授权用户手机号码
     *
     * @param code 授权码
     * @return 手机号码
     */
    public String getPhone(String code) throws WxErrorException {
        WxMaPhoneNumberInfo wxMaPhoneNumberInfo = wechatMiniProgramProperty.getWxMaService().getUserService().getNewPhoneNoInfo(code);
        return wxMaPhoneNumberInfo.getPhoneNumber();
    }

    public WechatMiniProgramHandler(WechatMiniProgramProperty wechatMiniProgramProperty) {
        this.wechatMiniProgramProperty = wechatMiniProgramProperty;
    }

    @Data
    @Configuration
    @ConfigurationProperties(prefix = "basicplatform.wechat.mini-program")
    public static class WechatMiniProgramProperty {
        /**
         * 应用Id
         */
        private String appId;
        /**
         * 应用秘钥
         */
        private String secret;

        public WxMaService getWxMaService() {
            WxMaDefaultConfigImpl wxMaConfig = new WxMaDefaultConfigImpl();
            wxMaConfig.setAppid(this.getAppId());
            wxMaConfig.setSecret(this.getSecret());
            wxMaConfig.setMsgDataFormat("JSON");
            WxMaService wxMaService = new WxMaServiceImpl();
            wxMaService.setWxMaConfig(wxMaConfig);
            return wxMaService;
        }
    }

}
